package main

import (
	"github.com/xgdapg/wtk"
	"net/url"
	"strconv"
	"strings"
)

type PluginSafeAdmin struct {
	Plugin
	server *wtk.Server
}

func init() {
	pluginManager.RegisterPlugin(&PluginSafeAdmin{})
}

func (this *PluginSafeAdmin) Start() {
	this.Plugin.Start()
	port, err := strconv.Atoi(this.Data)
	if err != nil {
		port = 443
		this.Data = "443"
		this.SaveData(this.Data)
	}
	wtk.SslCertificate = cfg.AppPath + "/cert.pem"
	wtk.SslCertificateKey = cfg.AppPath + "/key.pem"
	this.server = wtk.MainServer().Clone()
	go func() {
		this.server.Run("https", "", port)
	}()

	this.RegisterHook(wtk.HookAfterInit, func(h *wtk.HookHandler) {
		if strings.HasPrefix(h.Context.Request.URL.Path, "/admin") {
			if h.Context.Request.TLS == nil {
				u, _ := url.Parse(cfg.DomainPath)
				h.Context.RedirectUrl("https://" + strings.Split(u.Host, ":")[0] + ":" + strconv.Itoa(port) + h.Context.Request.URL.Path)
				return
			}
		}
	})
}

func (this *PluginSafeAdmin) Stop() {
	this.Plugin.Stop()
	if this.server != nil {
		this.server.Close()
	}
}
